//
// Created by guo on 24-8-16.
//

#include "shared_locker.h"

SharedLocker::SharedLocker() : _reader_nb(0),_writer_nb(0){

}

void SharedLocker::lock_shared() {
    std::unique_lock<std::mutex> lock(_mutex);
    while(_writer_nb > 0) {
        _cv_reader.wait(lock);
    }
    _reader_nb++;
}

void SharedLocker::unlock_shared() {
    std::lock_guard<std::mutex> lock(_mutex);
    _reader_nb--;
    _cv_reader.notify_all();
}

void SharedLocker::lock() {
    std::unique_lock<std::mutex> lock(_mutex);
    _writer_nb++;
    while(_reader_nb > 0 || _writer_nb > 1){
        _cv_writer.wait(lock);
    }
}

void SharedLocker::unlock() {
    std::lock_guard<std::mutex> lock(_mutex);
    _writer_nb--;
    _cv_writer.notify_all();
}
